<template>
  <div>
    <n-modal
      v-model:show="showModal"
      :mask-closable="false"
      :show-icon="false"
      preset="dialog"
      transform-origin="center"
      :title="formValue.id > 0 ? '编辑门店 #' + formValue.id : '添加门店'"
      :style="{
        width: dialogWidth,
      }"
    >
      <n-scrollbar style="max-height: 87vh" class="pr-5">
        <n-spin :show="loading" description="请稍候...">
          <n-form
            ref="formRef"
            :model="formValue"
            :rules="rules"
            :label-placement="settingStore.isMobile ? 'top' : 'left'"
            :label-width="100"
            class="py-4"
          >
            <n-grid cols="1 s:1 m:1 l:1 xl:1 2xl:1" responsive="screen">
              <n-gi span="1">
                <n-form-item label="门店名称" path="name">
                  <n-input placeholder="请输入门店名称" v-model:value="formValue.name" />
                </n-form-item>
              </n-gi>
              <n-gi span="1">
                <n-form-item label="门店电话" path="phone">
                  <n-input placeholder="请输入门店电话" v-model:value="formValue.phone" />
                </n-form-item>
              </n-gi>
              <!-- <n-gi span="1">
                <n-form-item label="营业星期" path="businessDay">
                  <n-checkbox-group v-model:value="formValue.businessDay">
                    <n-space item-style="display: flex;">
                      <n-checkbox :value="1" label="周一" />
                      <n-checkbox :value="2" label="周二" />
                      <n-checkbox :value="3" label="周三" />
                      <n-checkbox :value="4" label="周四" />
                      <n-checkbox :value="5" label="周五" />
                      <n-checkbox :value="6" label="周六" />
                      <n-checkbox :value="7" label="周日" />
                    </n-space>
                  </n-checkbox-group>
                </n-form-item>
              </n-gi>
              <n-gi span="1">
                <n-form-item label="营业时间" path="businessTime">
                  <n-space align="center">
                    <n-time-picker v-model:value="formValue.businessTimeStart" format="HH:mm" />
                    到
                    <n-time-picker v-model:value="formValue.businessTimeEnd" default-formatted-value="50400000" format="HH:mm" />
                  </n-space>
                </n-form-item>
              </n-gi> -->
              <n-gi span="1">
                <n-form-item label="关联商户" path="businessId">
                  <n-select v-model:value="formValue.businessId" placeholder="选择商户" :loading="loadingBusiness"  clearable
                    remote :options="searchBusinessResults"
                    label-field="label"
                    value-field="value"
                  />
                </n-form-item>
              </n-gi>
              <n-gi span="1">
                <n-form-item label="门店图片" path="publicityImgs">
                  <UploadImage :maxNumber="10" v-model:value="formValue.publicityImgs" />
                </n-form-item>
              </n-gi>
              <n-gi span="1">
                <n-form-item label="门店地址" path="address">
                  <n-input placeholder="请输入门店地址" v-model:value="formValue.address" />
                </n-form-item>
              </n-gi>
              <n-gi span="1">
                <n-form-item label="地图选点" path="map">
                  <iframe id="mapPage" width="100%" height="500px" frameborder=0 :src="mapSrc" style="margin: 0 auto;">
                  </iframe>
                </n-form-item>
              </n-gi>
              <n-gi span="1">
                <n-form-item label="纬度" path="lat" hidden>
                  <n-input-number placeholder="请输入纬度" v-model:value="formValue.lat" />
                </n-form-item>
              </n-gi>
              <n-gi span="1">
                <n-form-item label="经度" path="lng" hidden>
                  <n-input-number placeholder="请输入经度" v-model:value="formValue.lng" />
                </n-form-item>
              </n-gi>
              <n-gi span="1">
                <n-form-item label="地区编码" path="adcode" hidden>
                  <n-input-number placeholder="请输入地区编码" v-model:value="formValue.adcode" />
                </n-form-item>
              </n-gi>
            </n-grid>
          </n-form>
        </n-spin>
      </n-scrollbar>
      <template #action>
        <n-space>
          <n-button @click="closeForm">
            取消
          </n-button>
          <n-button type="info" :loading="formBtnLoading" @click="confirmForm">
            确定
          </n-button>
        </n-space>
      </template>
    </n-modal>
  </div>
</template>

<script lang="ts" setup>
  import { Geocoder } from '@/api/map/map';
import { List } from '@/api/org/user';
import { Edit, View } from '@/api/store';
import { getConfig } from '@/api/sys/config';
import { useProjectSettingStore } from '@/store/modules/projectSetting';
import { adaModalWidth } from '@/utils/hotgo';
import { FormItemRule, useMessage } from 'naive-ui';
import { computed, onMounted, ref } from 'vue';
import { State, newState } from './model';

  const emit = defineEmits(['reloadTable']);
  const message = useMessage();
  const settingStore = useProjectSettingStore();

  const loading = ref(false);
  const showModal = ref(false);
  const formValue = ref<State>(newState(null));
  const formRef = ref<any>({});
  const formBtnLoading = ref(false);
  const geoTencentWebKey = ref('');

  const coord = ref('');
  const mapSrc = ref('');

  const loadingBusiness = ref(false);

  const searchBusinessResults = ref<{ label: string; value: number }[]>([
    {
      label: '请选择',
      value: 0,
    },
  ]);

  const rules = {
    name: {
      required: true,
      trigger: ['input'],
      message: '请输入门店名称',
    },
    address: {
      required: true,
      trigger: ['input'],
      message: '请输入门店地址',
    },
    phone: {
      required: true,
      trigger: ['input'],
      message: '请输入门店电话',
    },
    // businessDay: {
    //   required: true,
    //   message: '请输入营业星期',
    // },
    // businessTime: {
    //   required: true,
    //   validator(rule: FormItemRule, value: any, callback: Function) {
    //     if (!formValue.value.businessTimeStart || !formValue.value.businessTimeEnd) {
    //       callback(new Error('请输入完整的营业时间'));
    //     } else {
    //       callback();
    //     }
    //   },
    // },
    publicityImgs: {
      required: true,
      message: '请上传门店图片',
    },
    map: {
      required: true,
      trigger: ['input'],
      // 自定义条件
      validator(rule: FormItemRule, value: string, callback: Function) {
        if (!formValue.value.lat || !formValue.value.lng) {
          callback(new Error('请选择地点'));
        } else {
          callback();
        }
      },
    },
  };

  // 嵌入的 JavaScript 代码
  onMounted(() => {
    window.addEventListener('message', function(event) {
      // 接收位置信息，用户选择确认位置点后选点组件会触发该事件，回传用户的位置信息
      var loc = event.data;
      if (loc && loc.module == 'locationPicker') { // 防止其他应用也会向该页面post信息，需判断module是否为'locationPicker'
        formValue.value.lat = loc.latlng.lat;
        formValue.value.lng = loc.latlng.lng;
        Geocoder({
          location: loc.latlng.lat + ',' + loc.latlng.lng,
          key: geoTencentWebKey.value,
        }).then((res) => {
          formValue.value.adcode = res.mapModel.result.ad_info.adcode;
        });
      }
    }, false);
  });


  const dialogWidth = computed(() => {
    return adaModalWidth(840);
  });

  // 提交表单
  function confirmForm(e) {
    e.preventDefault();
    formRef.value.validate((errors) => {
      if (!errors) {
        formBtnLoading.value = true;
        Edit(formValue.value)
          .then((_res) => {
            message.success('操作成功');
            closeForm();
            emit('reloadTable');
          })
          .finally(() => {
            formBtnLoading.value = false;
          });
      } else {
        message.error('请填写完整信息');
      }
    });
  }

  // 关闭表单
  function closeForm() {
    showModal.value = false;
    loading.value = false;
  }

  // 打开模态框
  function openModal(state: State) {
    showModal.value = true;

    loadingBusiness.value = true;
    List({ ...{ roleId: 213, storeType: 1, pageSize: 10000 } }).then((res) => {
      searchBusinessResults.value = [{
          label: '无',
          value: 0,
        }]
        
      searchBusinessResults.value.push(...res.list.map((item) => {
        return {
          label: item.storeName,
          value: item.id,
        };
      }));
      loadingBusiness.value = false;
    });

    // 新增
    if (!state || state.id < 1) {
      formValue.value = newState(state);
      getConfig({ group: 'geo' })
    .then((res) => {
      if (res?.list?.geoTencentWebKey) {
        geoTencentWebKey.value = res.list.geoTencentWebKey;
        mapSrc.value = `https://apis.map.qq.com/tools/locpicker?search=1&type=1&key=${geoTencentWebKey.value}&referer=myapp&zoom=18&coord=22.620478,114.03378`;
      }
    })
      return;
    }

    // 编辑
    loading.value = true;
    View({ id: state.id })
      .then((res) => {
        formValue.value = res;
        coord.value = formValue.value.lat + ',' + formValue.value.lng;
        getConfig({ group: 'geo' })
        .then((res) => {
          if (res?.list?.geoTencentWebKey) {
            geoTencentWebKey.value = res.list.geoTencentWebKey;
            mapSrc.value = `https://apis.map.qq.com/tools/locpicker?search=1&type=1&key=${geoTencentWebKey.value}&referer=myapp&zoom=18&coord=${coord.value}`;
          }
        })
      })
      .finally(() => {
        loading.value = false;
      });
  }

  defineExpose({
    openModal,
  });
</script>

<style lang="less"></style>